package com.yswl.yeeduo.asynctask;

import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.yswl.yeeduo.App;
import com.yswl.yeeduo.http.KAsyncTask;
import com.yswl.yeeduo.view.dialog.LoadingProgressDialog;

public abstract class BaseHttpTask<Params, Progress, Result> extends KAsyncTask<Params, Progress, Result> {
	private LoadingProgressDialog progressDialog;
	protected Context context;
	public BaseHttpTask(Context context,int taskId, com.yswl.yeeduo.http.KAsyncTask.TaskDelegate delegate) {
		super(taskId, delegate);
		this.context = context;
	}

	

	@Override
	protected void onCancelled() {
		super.setDelegate(null);
		super.onCancelled();
	}

	
	@Override
	protected void onPostExecute(Result result) {
		super.onPostExecute(result);
	}
	
	protected void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = LoadingProgressDialog.createDialog(context);
			progressDialog.setMessage("正在加载...");
			progressDialog.setCancelable(true);
		}

		progressDialog.show();
	}

	protected void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
	
	
	//TODO 返回结果
	public static final String RETURN_MSG = "msg";
	public static final String DATA = "data";
	public static final String RETURN_CODE = "status";//返回码
	public static boolean isSuccess(JSONObject json) {
		return isSuccess(json, true);
	}
	
	public static boolean isSuccess(JSONObject json, boolean notice) {
		if (json == null)
			return false;
		if (json.optInt(RETURN_CODE, -1) != 0) {
			if (notice) {
				String msg = getMSG(json);
				if (TextUtils.isEmpty(msg) || "null".equals(msg)) {
					msg = "异常操作";
				}
				Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
			}
			return false;
		}
		return true;
	}
	

	/**
	 * 获得数据说明
	 * 
	 * @param json
	 * @return
	 */
	public static String getMSG(JSONObject json) {
		return getMSG(json, "");
	}

	/**
	 * 获得数据说明
	 * 
	 * @param json
	 * @param 有缺省值
	 * @return 
	 */
	public static String getMSG(JSONObject json, String df) {
		if (json == null)
			return df;
		return json.optString(RETURN_MSG, df);
	}
	
	public static int getDATAINT(JSONObject json, String key, int defaultValue) {
		if (json == null)
			return defaultValue;
		return json.optInt(key, defaultValue);
	}

	public static Object getDATA(JSONObject json, String key) {
		if (json == null)
			return null;
		return json.opt(key);
	}
}
